/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.commons.util.print;

import java.awt.Graphics;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashAttributeSet;
import javax.print.attribute.standard.PrinterName;
import javax.swing.JOptionPane;
/**
 * 说明：
 * 会员消费小票打印
 * @Author：李智深
 * @Date：2012-05-11
 */
public class CashboxPrint extends Thread implements Printable {
	
	private String printName;
	public CashboxPrint(String printName){
		this.printName=printName;
	}
	
	/**
	 * * @param Graphic指明打印的图形环境 * @param
	 * PageFormat指明打印页格式（页面大小以点为计量单位，1点为1英寸的1/72，1英寸为25.4毫米。A4纸大致为595×842点） * @param
	 * pageIndex指明页号
	 **/
	@Override
	public int print(Graphics gra, PageFormat pf, int pageIndex)
			throws PrinterException {
		switch (pageIndex) {
		case 0:
			return PAGE_EXISTS;
		default:
			return NO_SUCH_PAGE;
		}
	}

	public void receiptsPrint() {
		Book book = new Book();
		
		PageFormat pf = new PageFormat();
		pf.setOrientation(PageFormat.PORTRAIT); // LANDSCAPE表示竖打;PORTRAIT表示横打;REVERSE_LANDSCAPE表示打印空白
		Paper p = new Paper();
		p.setImageableArea(0.4, 0.4, 0.4, 0.4); // A4(595 X
		pf.setPaper(p);
		book.append(this, pf);
		PrinterJob job = PrinterJob.getPrinterJob();
		job.setPageable(book);
		
		HashAttributeSet hs = new HashAttributeSet();
		hs.add(new PrinterName(printName, null));
		PrintService[] pss = PrintServiceLookup.lookupPrintServices(null, hs);
		if (pss.length == 0) {
			JOptionPane.showMessageDialog(null, "无法找到打印机:" + printName);
			return;
		}
		try {
			// 可以用printDialog显示打印对话框，在用户确认后打印；也可以直接打印
			job.setPrintService(pss[0]);
			job.print();
		} catch (PrinterException e) {
			JOptionPane.showMessageDialog(null, "请确定已经开启打印服务！");
			 e.printStackTrace();
		}
	}
	public void run(){
		receiptsPrint();
	}
	
	public static void main(String[] args) {
		new CashboxPrint("T58N").start();
	}
}
